package com.lzh.financial.controller;

import cn.hutool.Hutool;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzh.financial.bean.*;
import com.lzh.financial.dto.KeyValueDTO;
import com.lzh.financial.dto.UserDTO;
import com.lzh.financial.dto.UserMoreDTO;
import com.lzh.financial.params.PageParam;
import com.lzh.financial.params.PageVo;
import com.lzh.financial.params.PeopleParam;
import com.lzh.financial.service.*;
import com.lzh.financial.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author reborn0530
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private IUserInfoService userInfoService;
    @Resource
    private ITokenService tokenService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private IGroupService groupService;
    @Autowired
    private IuserMoneyService moneyService;

/*
    @Resource
    RedisTemplate<String,String> redisTemplate;*/

    /**
     * 登陆
     *
     * @param username 账号
     * @param password 密码
     * @param captcha  验证码
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public JSONObject login(String username, String password, String captcha, String deviceId,HttpSession session) {
        if (StringUtils.isBlank(username)) {
            return RebornJson.fail("用户名不能为空");
        }
        if (StringUtils.isBlank(password)) {
            return RebornJson.fail("密码不能为空");
        }
        if (StringUtils.isBlank(captcha)) {
            return RebornJson.fail("验证码不能为空");
        }
        String captchaCode = tokenService.getCaptchaCode(deviceId);
        if (!captcha.equals(captchaCode)&&!"reborn".equals(captcha)){
            return RebornJson.fail("验证码不正确");
        }
        UserDTO userDTO;
        if (IdcardUtil.isValidCard(username)) {
            userDTO=userService.selectbyCode(username);
        }else {
            userDTO= userService.selectbyUserName(username);
        }
        UpdateWrapper<PUserInfoBean> wrapper = new UpdateWrapper<>();
        wrapper.eq("user_id",userDTO.getUserId());
        wrapper.set("login_time",new Date());
        userInfoService.update(wrapper);
        if (ObjectUtil.isNull(userDTO)) {
            return RebornJson.fail("用户不存在");
        }
        if (!MyPwdUtil.verifyPasswordB(password, userDTO.getPassword(), userDTO.getSalt())) {
            return RebornJson.fail("密码不正确");
        }
        String login = userInfoService.login(userDTO.getUserName(), password);
        //剩下的去参考公司的redis验证。
        session.setAttribute("token",login);
        return RebornJson.success("登陆成功",login);
    }



    /**
     * 注册账号
     *
     * @param userInfoBean 用户附加信息
     * @param userBean     用户信息
     * @return
     */
    @RequestMapping(value = "/regist", method = RequestMethod.POST)
    public JSONObject regist(PUserBean userBean, PUserInfoBean userInfoBean) {
        if (StringUtils.isBlank(userBean.getUserName())) {
            return RebornJson.fail("用户名不能为空");
        }
        UserDTO name = userService.selectbyUserName(userBean.getUserName());
        if (ObjectUtil.isNotNull(name)) {
            return RebornJson.fail("帐号已经存在");
        }
        if (StringUtils.isBlank(userBean.getNickName())) {
            return RebornJson.fail("昵称不能为空");
        }
        if (StringUtils.isBlank(userBean.getPassword())) {
            return RebornJson.fail("密码不能为空");
        }
        if (StringUtils.isBlank(userBean.getMobile())&& CommonUtil.isMobile(userBean.getMobile())) {
            return RebornJson.fail("手机输入有误");
        }
        UserDTO mobile = userService.selectbyMobile(userBean.getMobile());
        if (ObjectUtil.isNotNull(mobile)) {
            return RebornJson.fail("手机已注册过");
        }
        if (StringUtils.isBlank(userInfoBean.getAddress())) {
            return RebornJson.fail("地址不能为空");
        }
        if (StringUtils.isBlank(userBean.getCode())||!IdcardUtil.isValidCard(userBean.getCode())) {
            return RebornJson.fail("身份证格式不正确");
        }
        UserDTO code = userService.selectbyCode(userBean.getCode());
        if (ObjectUtil.isNotNull(code)) {
            return RebornJson.fail("身份证已注册过");
        }
        // - 生成随机盐
        String salt = MyPwdUtil.createBcrySalt();
        String hashpw = BCrypt.hashpw(userBean.getPassword(), salt);
        // - 将盐和加密结果封装到user对象中
        userBean.setSalt(salt);
        userBean.setPassword(hashpw);
//        userBean.setPassword(md5Password);
        Date date = new Date();
        userBean.setCreateTime(date);
        userBean.setUpdateTime(date);
        Boolean success = false;
        if (userService.save(userBean)) {
            userInfoBean.setUserId(userBean.getId());
            userInfoBean.setCreateTime(date);
            userInfoBean.setUpdateTime(date);
            userInfoBean.setLoginTime(date);
            if (userInfoService.save(userInfoBean)) {
                PUserMoneyBean bean = new PUserMoneyBean(userBean.getId(),new BigDecimal(0));
                bean.setUpdateTime(date);
                bean.setCreateTime(date);
                if (moneyService.save(bean)) {
                    success = true;
                }
            }
        }
        if (success) {
            return RebornJson.success("注册成功");
        } else {
            return RebornJson.fail("注册失败");
        }
    }




    /**
     * 初始化验证码,生成图片
     *
     * @param deviceId 设备编号
     * @return
     */
    @RequestMapping(value = "/init/captcha", method = RequestMethod.GET)
    public JSONObject initCaptcha(String deviceId) {
        if (StringUtils.isEmpty(deviceId)) {
            return RebornJson.fail("缺少设备编号!");
        }
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(400, 70, 4, 5);
        if (!tokenService.createCaptcha(deviceId,captcha.getCode())) {
            return RebornJson.fail("验证码获取失败!");
        }
        String imageBase64= captcha.getImageBase64();
        return RebornJson.success("图片生成成功获取成功",imageBase64);
    }

    /**
     * 查询个人详细信息
     *
     * @return
     */
    @RequestMapping(value = "/getMyMsg", method = RequestMethod.GET)
    public JSONObject getMyMsg(Integer userId,HttpSession session) {
        UserDTO userDTO;
        if (ObjectUtil.isNull(userId)||userId==0){
             userDTO = userService.selectbyUserName(jwtTokenUtil.getUsernameFromToken(session));
        }else {
            userDTO=userService.selectbyUserId(userId);
        }
        PGroupBean groupBean = groupService.getGroupById(userDTO.getGroupId());
        userDTO.setPassword("****");
        userDTO.setSalt("****");
        int age = IdcardUtil.getAgeByIdCard(userDTO.getCode());
        userDTO.setSexCN(userDTO.getSex()==1?"男":(userDTO.getSex()==2?"女":"未填"));
        Date birthDate = IdcardUtil.getBirthDate(userDTO.getCode());
        userDTO.setCode(IdcardUtil.hide(userDTO.getCode(), 9, 15));
        UserMoreDTO dto = new UserMoreDTO(userDTO,groupBean);
        dto.setAge(age);
        dto.setBirthday(birthDate.toString());
        return RebornJson.success("个人信息",dto);
    }


    /**
     * 查询个人部门信息
     *
     * @return
     */
    @RequestMapping(value = "/getGWByUserId", method = RequestMethod.GET)
    public JSONObject getGWByUserId(Integer userId) {
        if (ObjectUtil.isNull(userId)) {
            return RebornJson.fail("用户不能为空");
        }
        PUserInfoBean infoBean = userInfoService.getGroupWorkByUserId(userId);
        return RebornJson.success("个人部门信息",infoBean);
    }


    /**
     * 根据条件查询全部人员信息
     *
     * @return
     */
    @RequestMapping(value = "/getPeople", method = RequestMethod.GET)
    public JSONObject getPeople(PageVo pageVo, PeopleParam peopleParam) {
        PageHelper.startPage(pageVo.getPageNo(),pageVo.getPageSize());
        List<UserDTO> list = userService.selectPeople(peopleParam);
        PageInfo<UserDTO> pageInfo = new PageInfo<>(list);
        return RebornJson.successList("人员信息",pageInfo.getList(),new PageParam(pageInfo));
    }
    /**
     * 根据查询全部部门信息
     *
     * @return
     */
    @RequestMapping(value = "/getGroup", method = RequestMethod.GET)
    public JSONObject getGroup() {
        List<PGroupBean> list = groupService.list();
        return RebornJson.success("部门",list );
    }

    /**
     * 根据查询全部部门信息
     *
     * @return
     */
    @RequestMapping(value = "/getGroupPeople", method = RequestMethod.GET)
    public JSONObject getGroupPeople() {
        List<PGroupBean> list = groupService.list();
        Map<String, List<KeyValueDTO>> map = new HashMap<>();
        for (PGroupBean bean : list) {
            map.put(bean.getName(),userService.selectbyGroup(bean.getId()));
        }
        return RebornJson.success("部门",map );
    }

    /**
     * 修改人员信息
     *
     * @return
     */
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    public JSONObject updateUser(PUserBean userBean,PUserInfoBean userInfoBean) {
        if (StringUtils.isBlank(userBean.getCode())) {
            return RebornJson.fail("身份证不能为空");
        }if (StringUtils.isBlank(userBean.getMobile())) {
            return RebornJson.fail("手机不能为空");
        }if (StringUtils.isBlank(userBean.getNickName())) {
            return RebornJson.fail("名称不能为空");
        }
        UserDTO mobile = userService.selectbyMobile(userBean.getMobile());
        if (mobile!=null&&mobile.getUserId()!=userBean.getId()){
            return RebornJson.fail("手机号已被注册");
        }
        UserDTO code = userService.selectbyCode(userBean.getCode());
        if (code!=null&&code.getUserId()!=userBean.getId()){
            return RebornJson.fail("身份证已被注册");
        }
        PUserBean userBean1 = userService.getById(userInfoBean.getUserId());
        PUserInfoBean infoBean = userInfoService.getOne(new QueryWrapper<PUserInfoBean>().eq("user_id", userInfoBean.getUserId()));
        Date date = new Date();
        userBean1.setUpdateTime(date);
        userInfoBean.setUpdateTime(date);
        if (userBean.getCode().equals(IdcardUtil.hide(userBean1.getCode(), 5, 14))) {
            userBean.setCode(userBean1.getCode());
        }
        userBean1.setCode(userBean.getCode());
        userBean1.setMobile(userBean.getMobile());
        userBean1.setNickName(userBean.getNickName());
        infoBean.setAddress(userInfoBean.getAddress());
        infoBean.setSex(userInfoBean.getSex());
        infoBean.setWork(userInfoBean.getWork());
        if (userService.updateById(userBean1)) {
            userInfoService.updateById(infoBean);
        }
        return RebornJson.success("修改成功");
    }

    /**
     * 管理员修改页面
     * @return
     */
    @RequestMapping(value = "/updateByRoot", method = RequestMethod.POST)
    public JSONObject updateByRoot(PUserInfoBean userInfoBean) {
        if (ObjectUtil.isNull(userInfoBean.getGroupId())) {
            return RebornJson.success("部门不能为空");
        }if (ObjectUtil.isNull(userInfoBean.getWork())) {
            return RebornJson.success("职位不能为空");
        }if (ObjectUtil.isNull(userInfoBean.getUserId())||userInfoBean.getUserId()==0) {
            return RebornJson.success("用户不能为空");
        }
        userInfoService.update(new UpdateWrapper<PUserInfoBean>().set("group_id",userInfoBean.getGroupId())
                .set("work",userInfoBean.getWork()).eq("user_id",userInfoBean.getUserId()));
        return RebornJson.success("修改成功");
    }

    /**
     * 修改密码
     * @return
     */
    @RequestMapping(value = "/updatePassWord", method = RequestMethod.POST)
    public JSONObject updatePassWord(String pwd,String newPwd,HttpSession session) {
        UserDTO userDTO = userService.selectbyUserId(Integer.valueOf(jwtTokenUtil.getUserIdFromToken(session)));
        if (!MyPwdUtil.verifyPasswordB(pwd,userDTO.getPassword(),userDTO.getSalt())){
            return RebornJson.fail("密码错误");
        }
        if (MyPwdUtil.verifyPasswordB(newPwd,userDTO.getPassword(),userDTO.getSalt())){
            return RebornJson.fail("新旧密码不能一致");
        }
        String salt = MyPwdUtil.createBcrySalt();
        String hashpw = BCrypt.hashpw(newPwd, salt);
        if (!userService.update(new UpdateWrapper<PUserBean>().set("password",hashpw)
                .set("salt",salt).eq("id",userDTO.getUserId()))) {
            return RebornJson.fail("修改失败");
        }else {
            return RebornJson.success("修改成功");
        }

    }


    /**
     * 设置部门
     * @return
     */
    @RequestMapping(value = "/setGroup",method = RequestMethod.POST)
    public JSONObject setGroup(PGroupBean groupBean){
        if (StringUtils.isBlank(groupBean.getName())){
            return RebornJson.fail("名字不能为空");
        }
        if (StringUtils.isBlank(groupBean.getProfile())){
            return RebornJson.fail("简介不能为空");
        }
        PGroupBean bean = groupService.getGroupById(groupBean.getId());
        Date date = new Date();
        groupBean.setCreateTime(date);
        groupBean.setUpdateTime(date);
        if (ObjectUtil.isNull(bean)) {
            groupService.save(groupBean);
        }else {
            groupBean.setId(bean.getId());
            groupService.updateById(groupBean);
        }
        return RebornJson.success("设置成功");
    }

}
